package com.net.xpay.core.helper;

import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.hash.Hashing;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.enums.user.SecurityStatus;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.common.exception.BusinessException;
import com.net.xpay.core.model.OpenBaseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 2020/6/28 10:39

 */
@Slf4j
@Component
public class SignerCheckHelper {
    @Autowired
    private UserManager userManager;

    @Autowired
    private EnvironmentHelper environmentHelper;

    public User checkSign(OpenBaseModel openBaseModel) {
        return checkSign(openBaseModel.getAppkey(), openBaseModel.getTimestamp(), openBaseModel.getSignature());
    }

    /**
     * 更严格的验证
     */
    public User checkSignV2(String appkey, String timestamp, String signature, String... params) {
        if (Strings.isNullOrEmpty(appkey)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "appkey不能为空");
        }

        if (Strings.isNullOrEmpty(timestamp)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "timestamp不能为空");
        }
        long time;
        try {
            time = Long.parseLong(timestamp);
        } catch (Exception e) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "时间戳格式错误");
        }
//        if (time > System.currentTimeMillis() + 1000L) {
//            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "时间戳不能大于当前时间");
//        }
        //5分后过期
//        if (!environmentHelper.isDevOrLocal()) {
//            if (System.currentTimeMillis() - time > 5 * 60 * 1000L) {
//                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请求已过期(请注意是否用的毫秒时间戳)");
//            }
//        }

        if (Strings.isNullOrEmpty(signature)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "signature不能为空");
        }
        User user = userManager.findByAppkey(appkey);
        if (user == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "用户不存在");
        }
        if (user.getSecurityStatus() != SecurityStatus.NORMAL) {
            log.info("checkSignV2 securityStatus error|userId={}", user.getId());
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "当前操作存在风险，请联系客服");
        }
        String secret = user.getSecret();

        String correctSign = Hashing.md5().hashString(appkey + secret + timestamp + Joiner.on("").join(params), Charsets.UTF_8).toString();
        if (!signature.equalsIgnoreCase(correctSign)) {
            log.warn("checkSignV2 signature error|appkey={}|secret={}|timestamp={}|signature={}", appkey, secret, timestamp, signature);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "签名错误");
        }
        return user;
    }


    public User checkSign(String appkey, String timestamp, String signature) {
        if (Strings.isNullOrEmpty(appkey)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "appkey不能为空");
        }

        if (Strings.isNullOrEmpty(timestamp)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "timestamp不能为空");
        }
        if (Strings.isNullOrEmpty(signature)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "signature不能为空");
        }
        User user = userManager.findByAppkey(appkey);
        if (user == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "用户不存在");
        }
        if (user.getSecurityStatus() != SecurityStatus.NORMAL) {
            log.info("checkSign securityStatus error|userId={}", user.getId());
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "当前操作存在风险，请联系客服");
        }
        String secret = user.getSecret();

        String correctSign = Hashing.md5().hashString(appkey + secret + timestamp, Charsets.UTF_8).toString();
        if (!signature.equalsIgnoreCase(correctSign)) {
            log.warn("checkSign signature error|appkey={}|secret={}|timestamp={}|signature={}", appkey, secret, timestamp, signature);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "签名错误");
        }
        return user;
    }

    public String sign(String appkey, String secret, String timestamp) {
        return Hashing.md5().hashString(appkey + secret + timestamp, Charsets.UTF_8).toString();
    }

    public String signV2(String appkey, String secret, String timestamp, String... params) {
        return Hashing.md5().hashString(appkey + secret + timestamp + Joiner.on("").join(params), Charsets.UTF_8).toString();
    }
}
